//
//  HZWebView.m
//  HZTC_YaDeArt
//
//  Created by MayerF on 17/4/10.
//  Copyright © 2017年 HZTC. All rights reserved.
//

#import "HZWebView.h"
#import "HZNativeAction.h"
#import "UIViewController+Root.h"

@interface HZWebView()<WKNavigationDelegate, WKScriptMessageHandler, WKUIDelegate>
@property (nonatomic, strong)UIActivityIndicatorView *pIndicatorView;
@end

@implementation HZWebView

#pragma mark -
#pragma mark 生命周期
- (instancetype)initWithFrame:(CGRect)frame{
    return [self initWithFrame:frame configuration:[self p_defaultConfiguration]];
}

- (instancetype)initWithFrame:(CGRect)frame configuration:(WKWebViewConfiguration *)configuration{
    self = [super initWithFrame:frame configuration:configuration];
    if (self) {
        [self p_commonInit];
    }
    return self;
}
#pragma mark -
#pragma mark private
- (void)p_commonInit
{
    self.navigationDelegate = self;
    self.UIDelegate = self;
//    [self setAllowsBackForwardNavigationGestures:YES];
    _pIndicatorView = [UIActivityIndicatorView new];
    _pIndicatorView.activityIndicatorViewStyle = UIActivityIndicatorViewStyleGray;
    
    self.scrollView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
    
    [self addSubview:_pIndicatorView];
    [self p_initConstraints];
}

- (void)p_initConstraints
{
    [_pIndicatorView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.mas_equalTo(self);
        make.width.mas_equalTo(50);
        make.height.mas_equalTo(50);
    }];
}

- (WKWebViewConfiguration *)p_defaultConfiguration
{
    WKWebViewConfiguration *config = [WKWebViewConfiguration new];
    //初始化偏好设置属性：preferences
    config.preferences = [WKPreferences new];
    //The minimum font size in points default is 0;
    config.preferences.minimumFontSize = 10;
    //是否支持JavaScript
    config.preferences.javaScriptEnabled = YES;
    //不通过用户交互，是否可以打开窗口
//    config.preferences.javaScriptCanOpenWindowsAutomatically = YES;
    
    [self addUserContentController:config];
    
    return config;
}

- (void)addUserContentController:(WKWebViewConfiguration *)config
{
    [config.userContentController addScriptMessageHandler:self name:@"tel"];
    [config.userContentController addScriptMessageHandler:self name:@"login"];
    [config.userContentController addScriptMessageHandler:self name:@"session"];
    [config.userContentController addScriptMessageHandler:self name:@"nav"];
    [config.userContentController addScriptMessageHandler:self name:@"stock"];
}

#pragma mark -
#pragma mark WKNavigationDelegate
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
    
    DLog(@"....%@", navigationAction.request.URL);
    NSString *scheme = [navigationAction.request.URL scheme];
    NSString *urlStr = [navigationAction.request.URL host];
    
    if ([scheme isEqual:@"stategyaction"]) {
        decisionHandler(WKNavigationActionPolicyCancel);
        LogicRouterBlock block = [self.logicManager matchLogicBlock:kLogicRouterWebStategyAction];
        if (block) {
            block(nil, urlStr);
        }
    }else if ([scheme isEqual:@"tel"]) {
        decisionHandler(WKNavigationActionPolicyCancel);
        LogicRouterBlock block = [self.logicManager matchLogicBlock:kLogicRouterWebTel];
        if (block) {
            block(nil, urlStr);
        }
    }else {
        decisionHandler(WKNavigationActionPolicyAllow);
    }
}

- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler {
    decisionHandler(WKNavigationResponsePolicyAllow);
    kBLOCK_SAFE_EXEC(_requestBlock)
}

- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation{
    DLog(@"didStartProvisionalNavigation");
    [_pIndicatorView startAnimating];
}
- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation{
    DLog(@"didCommitNavigation");
}
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
    DLog(@"didFinishNavigation");
    [_pIndicatorView stopAnimating];
    kBLOCK_SAFE_EXEC(_requestBlock)
    
    NSString *path = [[NSBundle mainBundle] pathForResource:@"nativeAction.js" ofType:nil];
    NSURL *jsurl = [NSURL fileURLWithPath:path];
    NSString *content = [NSString stringWithContentsOfURL:jsurl encoding:NSUTF8StringEncoding error:nil];
    [webView evaluateJavaScript:content completionHandler:nil];
}
- (void)webView:(WKWebView *)webView didFailNavigation:(WKNavigation *)navigation withError:(NSError *)error{
    DLog(@"didFailNavigation");
    [_pIndicatorView stopAnimating];
    kBLOCK_SAFE_EXEC(_requestBlock)
}

#pragma mark -
#pragma mark WKScriptMessageHandler
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
    NSLog(@"===%@", message.name);
    
    NSString *msgName = message.name;
    id body = message.body;
    
    if ([msgName isEqual:@"tel"]) {
        NSString *phone = @"";
        if ([body isKindOfClass:[NSString class]]) {
            phone = body;
        } else if ([body isKindOfClass:[NSNumber class]]) {
            phone = [body stringValue];
        }
        [HZNativeAction openPhone:phone];
        
    } else if ([msgName isEqual:@"login"]) {
        [HZNativeAction activeLogin];
        
    } else if ([msgName isEqual:@"session"]) {
        NSString *fun = [NSString stringWithFormat:@"%@('%@')", body, @"我是乔杨，还有谁"];
        [self evaluateJavaScript:fun completionHandler:nil];
        
//        UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"获取session" message:[NSString stringWithFormat:@"调用H5函数%@", fun] preferredStyle:UIAlertControllerStyleAlert];
//        UIAlertAction *ok = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//            [self evaluateJavaScript:fun completionHandler:nil];
//        }];
//        [alertVC addAction:ok];
//        [[UIViewController getCurrentViewController] presentViewController:alertVC animated:YES completion:nil];
        
    } else if ([msgName isEqual:@"nav"]) {
        kBLOCK_SAFE_EXEC(_changeNavTitleBlock, body)
        
    } else if ([msgName isEqual:@"stock"]) {
        kBLOCK_SAFE_EXEC(_jumpStockBlock, body)
    }
}

#pragma mark - WKUIDelegate
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler {
    
    NSLog(@"===");
    completionHandler();
}

@end
